using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MediPlatform.Read.Api.Models;
using MediPlatform.Read.Api.Services;
using MediPlatform.ErrorCode;
using MediPlatform.Infeartructure;

namespace MediPlatform.Read.Api.Controllers
{
    [ApiController]
    [Route("api/test/[controller]")]
    public class TestMedicalOrderController : ControllerBase
    {
        private readonly MedicalOrderService _medicalOrderService;
        private readonly ILogger<TestMedicalOrderController> _logger;

        public TestMedicalOrderController(
            MedicalOrderService medicalOrderService,
            ILogger<TestMedicalOrderController> logger)
        {
            _medicalOrderService = medicalOrderService;
            _logger = logger;
        }



        /// <summary>
        /// 测试获取订单详情
        /// </summary>
        [HttpGet("detail/{id}")]
        public async Task<ApiResult<MedicalOrderDetailResponse>> TestGetOrderDetail(long id)
        {
            try
            {
                var result = await _medicalOrderService.GetDetailAsync(id);
                if (result == null)
                {
                    return ApiResult<MedicalOrderDetailResponse>.Error("订单不存在");
                }
                return ApiResult<MedicalOrderDetailResponse>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试获取订单详情失败，ID：{Id}", id);
                return ApiResult<MedicalOrderDetailResponse>.Error("测试失败");
            }
        }

        /// <summary>
        /// 测试获取统计信息
        /// </summary>
        [HttpGet("statistics")]
        public async Task<ApiResult<MedicalOrderStatisticsResponse>> TestGetStatistics()
        {
            try
            {
                var result = await _medicalOrderService.GetStatisticsAsync();
                return ApiResult<MedicalOrderStatisticsResponse>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试获取统计信息失败");
                return ApiResult<MedicalOrderStatisticsResponse>.Error("测试失败");
            }
        }

        /// <summary>
        /// 测试分页功能
        /// </summary>
        [HttpGet("pagination")]
        public async Task<ApiResult<MedicalOrderPagedResponse>> TestPagination([FromQuery] int page = 1, [FromQuery] int size = 5)
        {
            try
            {
                var request = new MedicalOrderQueryRequest
                {
                    PageIndex = page,
                    PageSize = size
                };

                var result = await _medicalOrderService.GetPagedListAsync(request);
                return ApiResult<MedicalOrderPagedResponse>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试分页功能失败");
                return ApiResult<MedicalOrderPagedResponse>.Error("测试失败");
            }
        }

        /// <summary>
        /// 测试获取所有订单
        /// </summary>
        [HttpGet("all-orders")]
        public async Task<ApiResult<MedicalOrderPagedResponse>> TestGetAllOrders()
        {
            try
            {
                var request = new MedicalOrderQueryRequest
                {
                    PageIndex = 1,
                    PageSize = 10
                };

                var result = await _medicalOrderService.GetPagedListAsync(request);
                return ApiResult<MedicalOrderPagedResponse>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试获取全部订单失败");
                return ApiResult<MedicalOrderPagedResponse>.Error("测试失败");
            }
        }

        /// <summary>
        /// 测试获取待发货订单
        /// </summary>
        [HttpGet("pending-shipment")]
        public async Task<ApiResult<MedicalOrderPagedResponse>> TestGetPendingShipment()
        {
            try
            {
                var request = new MedicalOrderQueryRequest
                {
                    Status = 3, // 已拣货（待发货）
                    PageIndex = 1,
                    PageSize = 10
                };

                var result = await _medicalOrderService.GetPagedListAsync(request);
                return ApiResult<MedicalOrderPagedResponse>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试获取待发货订单失败");
                return ApiResult<MedicalOrderPagedResponse>.Error("测试失败");
            }
        }

        /// <summary>
        /// 测试获取待收货订单
        /// </summary>
        [HttpGet("pending-receipt")]
        public async Task<ApiResult<MedicalOrderPagedResponse>> TestGetPendingReceipt()
        {
            try
            {
                var request = new MedicalOrderQueryRequest
                {
                    Status = 4, // 已发货（待收货）
                    PageIndex = 1,
                    PageSize = 10
                };

                var result = await _medicalOrderService.GetPagedListAsync(request);
                return ApiResult<MedicalOrderPagedResponse>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试获取待收货订单失败");
                return ApiResult<MedicalOrderPagedResponse>.Error("测试失败");
            }
        }

        /// <summary>
        /// 测试获取已收货订单
        /// </summary>
        [HttpGet("received")]
        public async Task<ApiResult<MedicalOrderPagedResponse>> TestGetReceived()
        {
            try
            {
                var request = new MedicalOrderQueryRequest
                {
                    Status = 5, // 已签收（已收货）
                    PageIndex = 1,
                    PageSize = 10
                };

                var result = await _medicalOrderService.GetPagedListAsync(request);
                return ApiResult<MedicalOrderPagedResponse>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试获取已收货订单失败");
                return ApiResult<MedicalOrderPagedResponse>.Error("测试失败");
            }
        }

        /// <summary>
        /// 测试按订单号搜索
        /// </summary>
        [HttpGet("search-by-order-no")]
        public async Task<ApiResult<MedicalOrderPagedResponse>> TestSearchByOrderNo([FromQuery] string orderNo = "MO")
        {
            try
            {
                var request = new MedicalOrderQueryRequest
                {
                    OrderNoOrUsername = orderNo,
                    PageIndex = 1,
                    PageSize = 10
                };

                var result = await _medicalOrderService.GetPagedListAsync(request);
                return ApiResult<MedicalOrderPagedResponse>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试按订单号搜索失败");
                return ApiResult<MedicalOrderPagedResponse>.Error("测试失败");
            }
        }

        /// <summary>
        /// 测试按时间范围搜索
        /// </summary>
        [HttpGet("search-by-date-range")]
        public async Task<ApiResult<MedicalOrderPagedResponse>> TestSearchByDateRange([FromQuery] DateTime? startDate = null, [FromQuery] DateTime? endDate = null)
        {
            try
            {
                var request = new MedicalOrderQueryRequest
                {
                    StartTime = startDate ?? DateTime.Now.AddDays(-7),
                    EndTime = endDate ?? DateTime.Now,
                    PageIndex = 1,
                    PageSize = 10
                };

                var result = await _medicalOrderService.GetPagedListAsync(request);
                return ApiResult<MedicalOrderPagedResponse>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试按时间范围搜索失败");
                return ApiResult<MedicalOrderPagedResponse>.Error("测试失败");
            }
        }

        /// <summary>
        /// 测试数据库连接和表状态
        /// </summary>
        [HttpGet("database-status")]
        public async Task<ApiResult<object>> TestDatabaseStatus()
        {
            try
            {
                var context = _medicalOrderService.GetDbContext();
                var canConnect = await context.Database.CanConnectAsync();
                var orderCount = await context.MedicalOrder.CountAsync();
                var userCount = await context.User.CountAsync();

                var result = new
                {
                    DatabaseConnected = canConnect,
                    MedicalOrderCount = orderCount,
                    UserCount = userCount,
                    Timestamp = DateTime.Now
                };

                return ApiResult<object>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试数据库状态失败");
                return ApiResult<object>.Error($"数据库状态检查失败: {ex.Message}");
            }
        }
    }
} 